// test/test.js
import {
    getapplylistallapi,
    getWorkBench,
    settingmenuapi
} from '../../api/app.js'
import dayjs from 'dayjs'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isreturn: '',
        name: '',
        img: '',
        ischange: false,
        workBenchMenu: {
            '发薪': [{
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }],
            '风险管控': [{
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }],
            '管理': [{
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }]
        },
        hidden: true,
        flag: false,
        x: 0,
        y: 0,
        data: [{
                "id": 10,
                "menuName": "无卡发薪",
                "typeId": 0,
                "typeName": "发薪",
                "orderNum": 0,
                "path": "tab::/pages/index/index",
                "component": "",
                "visible": "0",
                "isDelete": "0",
                "icon": "https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/955b72b0-b34d-40bf-8198-4480ae69d073.jpg",
                "createUserId": "",
                "createTime": null,
                "updateUserId": "",
                "updateTime": null,
                "remark": "",
                "params": {}
            },
            {
                "id": 17,
                "menuName": "长期保",
                "typeId": 1,
                "typeName": "风险管控",
                "orderNum": 1,
                "path": "applet::/packageLongInsure/pages/index/index",
                "component": null,
                "visible": "0",
                "isDelete": "0",
                "icon": "https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/32c62d5d-c988-483e-b7b1-c08723f46e22.jpg",
                "createUserId": "",
                "createTime": null,
                "updateUserId": "",
                "updateTime": null,
                "remark": "",
                "params": {}
            },
            {
                "id": 14,
                "menuName": "日日保",
                "typeId": 1,
                "typeName": "风险管控",
                "orderNum": 2,
                "path": "applet::/packageInsurance/pages/insurance/insurance",
                "component": null,
                "visible": "0",
                "isDelete": "0",
                "icon": "https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/46b96900-1825-48d9-a4dc-ef9e39e6a347.jpg",
                "createUserId": "",
                "createTime": null,
                "updateUserId": "",
                "updateTime": null,
                "remark": "",
                "params": {}
            },
            {
                "id": 2,
                "menuName": "企业管理",
                "typeId": 2,
                "typeName": "管理",
                "orderNum": 2,
                "path": "applet::/pages/enterprise/enterprise",
                "component": null,
                "visible": "0",
                "isDelete": "0",
                "icon": "https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/f5d6370d-3f9d-46ff-9e64-3ff9e85ca038.jpg",
                "createUserId": "",
                "createTime": null,
                "updateUserId": "",
                "updateTime": null,
                "remark": "",
                "params": {}
            },
        ],
        disabled: true,
        elements: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getdom()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    flat(arr) {
        const result = [];
        const stack = [].concat(arr); // 将数组元素拷贝至栈，直接赋值会改变原数组
        //如果栈不为空，则循环遍历
        while (stack.length !== 0) {
            const val = stack.pop();
            if (Array.isArray(val)) {
                stack.push(...val); //如果是数组再次入栈，并且展开了一层
            } else {
                result.unshift(val); //如果不是数组就将其取出来放入结果数组中
            }
        }
        return result;
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 获取菜单列表
        getWorkBench().then(res => {
            getapplylistallapi({
                searchText: '',
                queryApplyDate: dayjs().format('YYYY-MM-DD'),
                applyStatus: 0
            }).then((resc) => {
                console.log((resc), 111111111)
                let arr = this.flat(resc)
                let len = arr.length
                res['发薪'].forEach((ele, i) => {
                    if (ele.menuName == "预支工资") {
                        ele.remark = len === 0 ? '' : len + ''
                    }
                })
                if (res['自定义'].length == 0) {
                    console.log(this.data.data);
                    this.data.data.forEach((ele, i) => {
                        res['自定义'].push(ele)
                    })
                } else if (res['自定义'][0].id === -1) {
                    res['自定义'] = []
                }
                this.setData({
                    data: res['自定义']
                })
                let arrc = Object.entries(res);
                arrc.pop();
                let newObj = Object.fromEntries(arrc);
                this.setData({
                    workBenchMenu: newObj
                })
                console.log(res, 'res')
            })
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },


    //长按
    _longtap: function (e) {
        const detail = e.detail;
        this.setData({
            ischange: true,
            x: e.currentTarget.offsetLeft,
            y: e.currentTarget.offsetTop,
            hidden: false,
            flag: true
        })
        wx.vibrateShort({
            type: 'heavy',
        })
    },
    add(e) {
        if (this.data.data.length >= 6) {
            wx.showToast({
                title: '最多可以添加6个',
                icon: 'none'
            })
            return
        } else {
            console.log(e.currentTarget.dataset.item);
            let isDuplicate = this.data.data.some(obj => obj.id === e.currentTarget.dataset.item.id);
            if (!isDuplicate) {
                this.data.data.push(e.currentTarget.dataset.item)
                this.setData({
                    data: this.data.data
                })
                this.getdom()
            } else {
                wx.showToast({
                    title: '已存在',
                    icon: 'none'
                })
            }
        }
        this.setData({
            isreturn: ''
        })
    },
    getdom() {
        var query = wx.createSelectorQuery();
        var nodesRef = query.selectAll(".item");
        nodesRef.fields({
            dataset: true,
            rect: true

        }, (result) => {
            this.setData({
                elements: result
            })
        }).exec()
    },
    del(e) {
        console.log(e);
        this.data.data.forEach((ele, i) => {
            if (ele.id === e.currentTarget.dataset.index) {
                this.data.data.splice(i, 1)
            }
        })
        this.setData({
            isreturn: '',
            data: this.data.data
        })
        this.getdom()
        // console.log(this.data.data);
        // e.currentTarget.dataset.index
    },
    //触摸开始
    touchs: function (e) {
        wx.pageScrollTo({
            scrollTop: 0
        })
        this.setData({
            isreturn: 'return'
        })
        this.getdom()
        console.log(e);
        this.setData({
            name: e.currentTarget.dataset.name,
            img: e.currentTarget.dataset.img,
            beginIndex: e.currentTarget.dataset.index
        })
    },
    //触摸结束
    touchend: function (e) {
        console.log(e);
        this.setData({
            ischange: false,
        })
        if (!this.data.flag) {
            return;
        }
        const x = e.changedTouches[0].pageX
        const y = e.changedTouches[0].pageY
        const list = this.data.elements;
        let data = this.data.data
        for (var j = 0; j < list.length; j++) {
            const item = list[j];
            if (x > item.left && x < item.right && y > item.top && y < item.bottom) {
                const endIndex = item.dataset.index;
                const beginIndex = this.data.beginIndex;
                //向后移动
                if (beginIndex < endIndex) {
                    console.log(1);
                    let tem = data[beginIndex];
                    for (let i = beginIndex; i < endIndex; i++) {
                        data[i] = data[i + 1]
                    }
                    data[endIndex] = tem;
                }
                //向前移动
                if (beginIndex > endIndex) {
                    console.log(2);
                    let tem = data[beginIndex];
                    for (let i = beginIndex; i > endIndex; i--) {
                        data[i] = data[i - 1]
                    }
                    data[endIndex] = tem;
                }

                this.setData({
                    data: data
                })
                console.log(this.data.data);
                console.log(this.datainit(this.data.data));
            }
        }
        this.setData({
            hidden: true,
            flag: false,
            isreturn: ''
        })
    },
    async onSave() {
        await this.settingmenu(this.datainit(this.data.data))
        await wx.showToast({
            title: '保存成功',
            icon: 'none'
        })
        await wx.navigateBack()
    },
    //滑动
    touchm: function (e) {
        console.log(e);
        if (this.data.flag) {
            const x = e.touches[0].pageX
            const y = e.touches[0].pageY
            this.setData({
                x: x - 75,
                y: y - 100
            })
        }
    },
    datainit(arr) {
        let sendarr = []
        if (arr.length === 0) {
            sendarr = [{
                payMenuId: -1,
                sort: -1
            }]
        } else {
            arr.forEach((ele, i) => {
                sendarr.push({
                    payMenuId: ele.id,
                    sort: i
                })
            })
        }
        return sendarr
    },
    // 常用应用排序
    async settingmenu(arr) {
        let res = await settingmenuapi({
            menuInfos: arr
        })
    }
})